
<!doctype html>
<html class="theme-next use-motion theme-next-mala">
<head>
  

<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>




<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>


    <meta name="description" content="人皆可以為堯舜" />



  <meta name="keywords" content="TypeScript," />



  <link rel="alternate" href="/atom.xml" title="minichn's blog" type="application/atom+xml" />



  <link rel="shorticon icon" type="image/x-icon" href="/myimg/favicon.ico?v=0.4.5.1" />


<meta name="description" content="什么是TypeScript？TypeScript是JavaScript的一个超集，提供了类型系统和对ES6的支持，它可以编译成纯JavaScript。 TypeScript由Microsoft开发且开源。 为什么选择TypeScript？1、增加了代码的可读性和可维护性类型系统实际上是最好的文档，大部分的函数看看类型的定义就可以知道如何使用了可以在编译阶段就发现大部分错误，这总比在运行时候出错好增">
<meta name="keywords" content="TypeScript">
<meta property="og:type" content="article">
<meta property="og:title" content="御剑TypeScript">
<meta property="og:url" content="https://cmini777.gitee.io/2019/08/13/御剑TypeScript/index.html">
<meta property="og:site_name" content="minichn&#39;s blog">
<meta property="og:description" content="什么是TypeScript？TypeScript是JavaScript的一个超集，提供了类型系统和对ES6的支持，它可以编译成纯JavaScript。 TypeScript由Microsoft开发且开源。 为什么选择TypeScript？1、增加了代码的可读性和可维护性类型系统实际上是最好的文档，大部分的函数看看类型的定义就可以知道如何使用了可以在编译阶段就发现大部分错误，这总比在运行时候出错好增">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-08-13T10:49:34.301Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="御剑TypeScript">
<meta name="twitter:description" content="什么是TypeScript？TypeScript是JavaScript的一个超集，提供了类型系统和对ES6的支持，它可以编译成纯JavaScript。 TypeScript由Microsoft开发且开源。 为什么选择TypeScript？1、增加了代码的可读性和可维护性类型系统实际上是最好的文档，大部分的函数看看类型的定义就可以知道如何使用了可以在编译阶段就发现大部分错误，这总比在运行时候出错好增">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mala',
    sidebar: 'post'
  };
</script>
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <title> 御剑TypeScript | minichn's blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">匠心沈澱</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            <i class="menu-item-icon icon-next-categories"></i> <br />
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            <i class="menu-item-icon icon-next-about"></i> <br />
            关于
          </a>
        </li>
      

      
      
    </ul>
  

  
    <div class="site-search">
      
  
      <form class="site-search-form">
        <input type="text" id="local-search-input" class="st-search-input st-default-search-input" />
      </form>
      <div id="local-search-result" class="search-result-show"></div>
      <script type="text/javascript" src="/js/search.js"></script>

      


    </div>
  
</nav>

 </div>
    </header>

    
      

      
        <style type="text/css">

    .circle {
        width: 40px;
        height: 40px;
        background: #555 no-repeat;
        cursor: move;
    }

    .assist-btn {
        position: fixed;
        top: 50％;
        left: 10px;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
        outline: none;
        border: none;
        color: #87daff;
    }

</style>

<script type="text/javascript">
    // 浮动圆点展开与收缩
    /*
    $(function () {
        var assist_box = $('.assist-box');
        $('#assist_btn').hover(function () {
            assist_box.stop().show(300);
        }, function () {
            assist_box.stop().hide(150);
        })
    });
    */  
    //浮动圆点拖动
    $(function () {
        var box = document.getElementById('assist_btn');
        box.onmousedown = function (event) {
            var e = event || window.event,
                t = e.target || e.srcElement,
                // 鼠标按下时的坐标x1,y1
                x1 = e.clientX,
                y1 = e.clientY,
                //鼠标按下时的左右偏移量
                dragLeft = this.offsetLeft,
                dragTop = this.offsetTop;

            document.onmousemove = function (event) {
                var e = event || window.event,
                    t = e.target || e.srcElement,
                    // 鼠标移动时的动态坐标
                    x2 = e.clientX,
                    y2 = e.clientY,
                    // 鼠标移动时的坐标的变化量
                    x = x2 - x1,
                    y = y2 - y1;
                box.style.left = (dragLeft + x) + 'px';
                box.style.top = (dragTop + y) + 'px';
            }

            document.onmouseup = function () {
                this.onmousemove = null;
            }
        }
    });

/*
    $whitesmoke   = #f5f5f5
    $gainsboro    = #eee
    $gray-lighter = #ddd
    $grey-light   = #ccc
    $grey         = #bbb
    $grey-dark    = #999
    $grey-dim     = #666
    $black-light  = #555
    $black-deep   = #222
    $red          = #ff2a2a
    $blue-bright  = #87daff
    $blue         = #0684bd
    $blue-deep    = #262a30
*/
    // white theme
    var body = {color: "#555", background: "white"};
    var a_tag = {color: "#222"};
    var header = { background: "#f5f5f5"};
    var logo_line_i = {background: "#222"};
    // var post_code = {background: "#eee", color: "#222"};

    function switch_theme() {
        $("body").css(body);
        $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
        $(".header, .footer").css(header);
        $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
        //$(".post code").css(post_code);
        $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
        $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
        
        // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
        $("#assist_btn").hide(1500);
    }

    $(function () {
        $("#assist_btn").dblclick(function() {
            switch_theme();
        });
    });

</script>

<div>

    <button class="assist-btn circle" id="assist_btn" title="双击切换">
        亮
    </button>

</div>









      

    

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              御剑TypeScript
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2019-08-13T16:58:32+08:00" content="2019-08-13">
            2019-08-13
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 分类于
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/TypeScript/" itemprop="url" rel="index">
                  <span itemprop="name">TypeScript</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><h1 id="什么是TypeScript？"><a href="#什么是TypeScript？" class="headerlink" title="什么是TypeScript？"></a>什么是TypeScript？</h1><p>TypeScript是JavaScript的一个超集，提供了类型系统和对ES6的支持，它可以编译成纯JavaScript。 TypeScript由Microsoft开发且开源。</p>
<h1 id="为什么选择TypeScript？"><a href="#为什么选择TypeScript？" class="headerlink" title="为什么选择TypeScript？"></a>为什么选择TypeScript？</h1><p>1、增加了代码的可读性和可维护性<br>类型系统实际上是最好的文档，大部分的函数看看类型的定义就可以知道如何使用了<br>可以在编译阶段就发现大部分错误，这总比在运行时候出错好<br>增强了编辑器和 IDE 的功能，包括代码补全、接口提示、跳转到定义、重构等<br>2、TypeScript非常包容<br>TypeScript 是 JavaScript 的超集，.js 文件可以直接重命名为 .ts 即可<br>即使不显式的定义类型，也能够自动做出类型推论<br>可以定义从简单到复杂的几乎一切类型<br>即使 TypeScript 编译报错，也可以生成 JavaScript 文件<br>兼容第三方库，即使第三方库不是用 TypeScript 写的，也可以编写单独的类型文件供 TypeScript 读取<br>3、拥有活跃的社区</p>
<h1 id="使用TypeScript"><a href="#使用TypeScript" class="headerlink" title="使用TypeScript"></a>使用TypeScript</h1><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install -g typescript //安装TypeScript</span><br><span class="line">tsc hello.ts              //编译TypeScript文件,这时候会生成一个编译好的文件hello.js</span><br></pre></td></tr></table></figure>
<p>TypeScript 中，使用 : 指定变量的类型，: 的前后有没有空格都可以。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> sayHello(person: string) &#123;</span><br><span class="line">    <span class="built_in">return</span> <span class="string">'Hello, '</span> + person;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">let</span> user = <span class="string">'Tom'</span>;</span><br><span class="line">console.log(sayHello(user));</span><br></pre></td></tr></table></figure></p>
<p>上述例子中，我们用 : 指定 person 参数类型为 string。let是ES6中的关键字，和var类似，用于定义一个局部变量，所声明的变量，只在let命令所在的代码块内有效。据此，for循环的计数器，就很合适使用let命令。令，let所声明的变量一定要在声明后使用，否则报错。</p>
<h2 id="原始数据类型"><a href="#原始数据类型" class="headerlink" title="原始数据类型"></a>原始数据类型</h2><p>JavaScript 的类型分为两种：原始数据类型和对象类型。<br>原始数据类型包括：布尔值、数值、字符串、null、undefined 以及 ES6 中的新类型 Symbol。</p>
<h3 id="在-TypeScript-中，使用-boolean-定义布尔值类型："><a href="#在-TypeScript-中，使用-boolean-定义布尔值类型：" class="headerlink" title="在 TypeScript 中，使用 boolean 定义布尔值类型："></a>在 TypeScript 中，使用 boolean 定义布尔值类型：</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> isDone: boolean = <span class="literal">false</span>;</span><br></pre></td></tr></table></figure>
<p>注意，使用构造函数 Boolean 创造的对象不是布尔值，而是一个Boolean对象：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> createdByNewBoolean: Boolean = new Boolean(1);</span><br></pre></td></tr></table></figure></p>
<p>直接调用 Boolean 也可以返回一个 boolean 类型：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> createdByBoolean: boolean = Boolean(1);</span><br></pre></td></tr></table></figure></p>
<p>在 TypeScript 中，boolean 是 JavaScript 中的基本类型，而 Boolean 是 JavaScript 中的构造函数。其他基本类型（除了 null 和 undefined）一样，不再赘述。</p>
<h3 id="数值"><a href="#数值" class="headerlink" title="数值"></a>数值</h3><p>使用 number 定义数值类型：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> decLiteral: number = 6;</span><br></pre></td></tr></table></figure></p>
<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><p>使用 string 定义字符串类型：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> myName: string = <span class="string">'Tom'</span>;</span><br><span class="line"><span class="built_in">let</span> myAge: number = 25;</span><br><span class="line"></span><br><span class="line">// 模板字符串</span><br><span class="line"><span class="built_in">let</span> sentence: string = `Hello, my name is <span class="variable">$&#123;myName&#125;</span>.</span><br><span class="line">I<span class="string">'ll be $&#123;myAge + 1&#125; years old next month.`;</span></span><br></pre></td></tr></table></figure></p>
<p>其中<code>用来定义ES6中的模板字符串（ES6 引入了模板字符串，用反引号</code>标识，它可以当作普通字符串使用，也可以用来定义多行字符串，或者在字符串中嵌入变量），${expr} 用来在模板字符串中嵌入表达式。</p>
<h3 id="空值"><a href="#空值" class="headerlink" title="空值"></a>空值</h3><p>JavaScript 没有空值（Void）的概念，在 TypeScript 中，可以用 void 表示没有任何返回值的函数：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> alertName(): void &#123;</span><br><span class="line">    alert(<span class="string">'My name is Tom'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="Null-和-Undefined"><a href="#Null-和-Undefined" class="headerlink" title="Null 和 Undefined"></a>Null 和 Undefined</h3><p>在 TypeScript 中，可以使用 null 和 undefined 来定义这两个原始数据类型：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> u: undefined = undefined;</span><br><span class="line"><span class="built_in">let</span> n: null = null;</span><br></pre></td></tr></table></figure></p>
<p>undefined 类型的变量只能被赋值为 undefined，null 类型的变量只能被赋值为 null</p>
<h2 id="任意值类型"><a href="#任意值类型" class="headerlink" title="任意值类型"></a>任意值类型</h2><p>any 类型允许被赋值为任意类型。如果是一个普通类型，在赋值过程中改变类型是不被允许的。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> myFavoriteNumber: any = <span class="string">'seven'</span>;</span><br><span class="line">myFavoriteNumber = 7;</span><br></pre></td></tr></table></figure></p>
<p>在任意值上访问任何属性都是允许的：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> anyThing: any = <span class="string">'hello'</span>;</span><br><span class="line">console.log(anyThing.myName);</span><br><span class="line">console.log(anyThing.myName.firstName);</span><br></pre></td></tr></table></figure></p>
<p>也允许调用任何方法：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> anyThing: any = <span class="string">'Tom'</span>;</span><br><span class="line">anyThing.setName(<span class="string">'Jerry'</span>);</span><br><span class="line">anyThing.setName(<span class="string">'Jerry'</span>).sayHello();</span><br><span class="line">anyThing.myName.setFirstName(<span class="string">'Cat'</span>);</span><br></pre></td></tr></table></figure></p>
<p>可以认为，声明一个变量为任意值之后，对它的任何操作，返回的内容的类型都是任意值。<br>变量如果在声明的时候，未指定其类型，那么它会被识别为任意值类型：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> something;</span><br><span class="line">something = <span class="string">'seven'</span>;</span><br><span class="line">something = 7;</span><br><span class="line"></span><br><span class="line">something.setName(<span class="string">'Tom'</span>);</span><br></pre></td></tr></table></figure></p>
<p>等价于<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> something: any;</span><br><span class="line">something = <span class="string">'seven'</span>;</span><br><span class="line">something = 7;</span><br><span class="line"></span><br><span class="line">something.setName(<span class="string">'Tom'</span>);</span><br></pre></td></tr></table></figure></p>
<h2 id="类型推论"><a href="#类型推论" class="headerlink" title="类型推论"></a>类型推论</h2><p>以下代码虽然没有指定类型，但是会在编译的时候报错：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> myFavoriteNumber = <span class="string">'seven'</span>;</span><br><span class="line">myFavoriteNumber = 7;</span><br></pre></td></tr></table></figure></p>
<p>事实上，它等价于：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> myFavoriteNumber: string = <span class="string">'seven'</span>;</span><br><span class="line">myFavoriteNumber = 7;</span><br></pre></td></tr></table></figure></p>
<p>TypeScript 会在没有明确的指定类型的时候推测出一个类型，这就是类型推论。<br>如果定义的时候没有赋值，不管之后有没有赋值，都会被推断成 any 类型而完全不被类型检查。</p>
<h2 id="联合类型"><a href="#联合类型" class="headerlink" title="联合类型"></a>联合类型</h2><p>联合类型表示取值可以为多种类型中的一种。<br>联合类型使用 | 分隔每个类型。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> myFavoriteNumber: string | number;</span><br><span class="line">myFavoriteNumber = <span class="string">'seven'</span>;</span><br><span class="line">myFavoriteNumber = 7;</span><br></pre></td></tr></table></figure></p>
<p>这里的 let myFavoriteNumber: string | number 的含义是，允许 myFavoriteNumber 的类型是 string 或者 number，但是不能是其他类型。</p>
<h2 id="对象的类型——接口"><a href="#对象的类型——接口" class="headerlink" title="对象的类型——接口"></a>对象的类型——接口</h2><p>在 TypeScript 中，我们使用接口（Interfaces）来定义对象的类型。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">interface Person &#123;</span><br><span class="line">    name: string;</span><br><span class="line">    age: number;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">let</span> tom: Person = &#123;</span><br><span class="line">    name: <span class="string">'Tom'</span>,</span><br><span class="line">    age: 25</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>上面的例子中，我们定义了一个接口 Person，接着定义了一个变量 tom，它的类型是 Person。这样，我们就约束了 tom 的形状必须和接口 Person 一致。（接口一般首字母大写）</p>
<h3 id="可选属性"><a href="#可选属性" class="headerlink" title="可选属性"></a>可选属性</h3><p>有时我们希望不要完全匹配一个形状，那么可以用可选属性：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">interface Person &#123;</span><br><span class="line">    name: string;</span><br><span class="line">    age?: number;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">let</span> tom: Person = &#123;</span><br><span class="line">    name: <span class="string">'Tom'</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>可选属性的含义是该属性可以不存在。</p>
<h2 id="数组的类型"><a href="#数组的类型" class="headerlink" title="数组的类型"></a>数组的类型</h2><p>在 TypeScript 中，数组类型有多种定义方式，比较灵活。<br>「类型 + 方括号」表示法<br>最简单的方法是使用「类型 + 方括号」来表示数组：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> fibonacci: number[] = [1, 1, 2, 3, 5];</span><br></pre></td></tr></table></figure></p>
<p>数组泛型<br>泛型是指在定义函数、接口或类的时候，不预先指定具体的类型，而在使用的时候再指定类型的一种特性。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//也可以使用数组泛型Array&lt;elemType&gt;来表示数组：</span><br><span class="line"><span class="built_in">let</span> fibonacci: Array&lt;number&gt; = [1, 1, 2, 3, 5];</span><br></pre></td></tr></table></figure></p>
<p>接口也可以用来描述数组：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">interface NumberArray &#123;</span><br><span class="line">    [index: number]: number;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">let</span> fibonacci: NumberArray = [1, 1, 2, 3, 5];</span><br></pre></td></tr></table></figure></p>
<p>NumberArray 表示：只要 index 的类型是 number，那么值的类型必须是 number。</p>
<h2 id="函数的类型"><a href="#函数的类型" class="headerlink" title="函数的类型"></a>函数的类型</h2><p>一个函数有输入和输出，要在 TypeScript 中对其进行约束，需要把输入和输出都考虑到，其中函数声明的类型定义较简单：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> sum(x: number, y: number): number &#123;</span><br><span class="line">    <span class="built_in">return</span> x + y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意，输入多余的（或者少于要求的）参数，是不被允许的。<br>如果要我们现在写一个对函数表达式（Function Expression）的定义，可能会写成这样：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> mySum = <span class="keyword">function</span> (x: number, y: number): number &#123;</span><br><span class="line">    <span class="built_in">return</span> x + y;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>这是可以通过编译的，不过事实上，上面的代码只对等号右侧的匿名函数进行了类型定义，而等号左边的 mySum，是通过赋值操作进行类型推论而推断出来的。如果需要我们手动给 mySum 添加类型，则应该是这样：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> mySum: (x: number, y: number) =&gt; number = <span class="keyword">function</span> (x: number, y: number): number &#123;</span><br><span class="line">    <span class="built_in">return</span> x + y;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>注意不要混淆了 TypeScript 中的 =&gt; 和 ES6 中的 =&gt;。<br>在 TypeScript 的类型定义中，=&gt; 用来表示函数的定义，左边是输入类型，需要用括号括起来，右边是输出类型。</p>
<p>在 ES6 中，=&gt; 叫做箭头函数，ES6 允许使用“箭头”（=&gt;）定义函数。以下为ES6箭头函数：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var f = v =&gt; v;</span><br><span class="line"></span><br><span class="line">// 等同于</span><br><span class="line">var f = <span class="keyword">function</span> (v) &#123;</span><br><span class="line">  <span class="built_in">return</span> v;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>如果箭头函数不需要参数或需要多个参数，就使用一个圆括号代表参数部分。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var f = () =&gt; 5;</span><br><span class="line">// 等同于</span><br><span class="line">var f = <span class="function"><span class="title">function</span></span> () &#123; <span class="built_in">return</span> 5 &#125;;</span><br><span class="line"></span><br><span class="line">var sum = (num1, num2) =&gt; num1 + num2;</span><br><span class="line">// 等同于</span><br><span class="line">var sum = <span class="keyword">function</span>(num1, num2) &#123;</span><br><span class="line">  <span class="built_in">return</span> num1 + num2;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>具体可见<a href="http://es6.ruanyifeng.com/#docs/function#箭头函数" target="_blank" rel="noopener">ES6 中的箭头函数</a></p>
<h2 id="类型断言"><a href="#类型断言" class="headerlink" title="类型断言"></a>类型断言</h2><p>类型断言可以用来手动指定一个值的类型。<br>语法<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;类型&gt;值</span><br></pre></td></tr></table></figure></p>
<p>或<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">值 as 类型</span><br></pre></td></tr></table></figure></p>
<p>在 tsx 语法（React 的 jsx 语法的 ts 版）中必须用后一种。<br>有时候，我们需要在还不确定类型的时候就访问其中一个类型的属性或方法。此时可以使用类型断言：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> getLength(something: string | number): number &#123;</span><br><span class="line">    <span class="keyword">if</span> ((&lt;string&gt;something).length) &#123;</span><br><span class="line">        <span class="built_in">return</span> (&lt;string&gt;something).length;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">return</span> something.toString().length;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>类型断言的用法如上，在需要断言的变量前加上 Type 即可。<br>类型断言不是类型转换，断言成一个联合类型中不存在的类型是不允许的。</p>
</span>
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/TypeScript/" rel="tag">#TypeScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/14/POJO搬到龙目岛——Lombok/" rel="prev">POJO搬到龙目岛——Lombok</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/13/React整合ECharts/" rel="next">React整合ECharts</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div>
      
    </div>

    <div class="post-spread">
      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" src="/images/default_avatar.jpg" alt="minichn" itemprop="image"/>
          <p class="site-author-name" itemprop="name">minichn</p>
        </div>
        <p class="site-description motion-element" itemprop="description">人皆可以為堯舜</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">14</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            <a href="/categories">
              <span class="site-state-item-count">12</span>
              <span class="site-state-item-name">分类</span>
              </a>
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">16</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <!-- <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div> -->
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/CMINI777" target="_blank">GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://gitee.com/CMINI777" target="_blank">Gitee</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/chnguo/activities" target="_blank">ZhiHu</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://cmini777.gitee.io/about/" target="_blank">MiniCHN</a>
              </span>
            
          
        </div>

        <div class="links-of-friendly motion-element">
          
            <p class="site-author-name">友情链接</p>
            
              <span class="links-of-author-item">
              <a href="http://blog.idhyt.com/about/" target="_blank">idhyt</a>
              </span>
            
              <span class="links-of-author-item">
              <a href="https://blog.guxiangfly.cn/" target="_blank">guxiangfly</a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="http://creativecommons.org/licenses/by-nc-sa/4.0" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#什么是TypeScript？"><span class="nav-number">1.</span> <span class="nav-text">什么是TypeScript？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么选择TypeScript？"><span class="nav-number">2.</span> <span class="nav-text">为什么选择TypeScript？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用TypeScript"><span class="nav-number">3.</span> <span class="nav-text">使用TypeScript</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#原始数据类型"><span class="nav-number">3.1.</span> <span class="nav-text">原始数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#在-TypeScript-中，使用-boolean-定义布尔值类型："><span class="nav-number">3.1.1.</span> <span class="nav-text">在 TypeScript 中，使用 boolean 定义布尔值类型：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数值"><span class="nav-number">3.1.2.</span> <span class="nav-text">数值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串"><span class="nav-number">3.1.3.</span> <span class="nav-text">字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#空值"><span class="nav-number">3.1.4.</span> <span class="nav-text">空值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Null-和-Undefined"><span class="nav-number">3.1.5.</span> <span class="nav-text">Null 和 Undefined</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#任意值类型"><span class="nav-number">3.2.</span> <span class="nav-text">任意值类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类型推论"><span class="nav-number">3.3.</span> <span class="nav-text">类型推论</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#联合类型"><span class="nav-number">3.4.</span> <span class="nav-text">联合类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对象的类型——接口"><span class="nav-number">3.5.</span> <span class="nav-text">对象的类型——接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#可选属性"><span class="nav-number">3.5.1.</span> <span class="nav-text">可选属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组的类型"><span class="nav-number">3.6.</span> <span class="nav-text">数组的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的类型"><span class="nav-number">3.7.</span> <span class="nav-text">函数的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类型断言"><span class="nav-number">3.8.</span> <span class="nav-text">类型断言</span></a></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp;  2018 - 
  <span itemprop="copyrightYear">2019
  </span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">minichn
  </span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme by <a class="theme-link" href="https://cmini777.gitee.io/">minichn</a>.<a class="theme-link" href="https://gitee.com/CMINI777/next-minichn">next-minichn</a>
</div>

<!-- busuanzi -->



 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  
  
  
    
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>
</body>
</html>
